import os,shutil,sys
from PIL import Image

# 获取文件夹下所有文件路径
def get_file_paths(directory):
    file_paths = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_paths.append(os.path.join(root, file))
    return file_paths

def convert_png_to_jpg(png_path, jpg_path):
    img = Image.open(png_path)
    if img.mode != 'RGB':
        img = img.convert('RGB')
    try:
        img.save(jpg_path, 'JPEG')
        os.remove(png_path)
    except IOError:
        print("cannot convert", png_path)

def is_file_larger_than_2mb(file_path):
    # 2MB等于2097152字节
    two_mb = 2 * 1024 * 1024
    # 获取文件大小
    file_size = os.path.getsize(file_path)
    # 判断文件大小是否大于2MB
    return file_size > two_mb

dir="D:/Desk/TEMU-批量上款/1-内容分组/"

# PNG 转换成JPG
paths= get_file_paths("D:/Desk/TEMU-批量上款/0-浏览器下载")
for path in paths:
    if 'png' in path and 'pic' not in path:
        jpg_path=path.replace('png','jpg')
        convert_png_to_jpg(path,jpg_path)
paths= get_file_paths("D:/Desk/TEMU-批量上款/0-浏览器下载")

# 查询是否在大于2M的文件       
for path in paths:
    if is_file_larger_than_2mb(path) and 'pic' not in path:
        name=os.path.basename(path)
        print(name,":文件大于2MB 程序终止")
        sys.exit()

# 文件整理                
paths= get_file_paths("D:/Desk/TEMU-批量上款/0-浏览器下载")       
for path in paths:
    file=os.path.basename(path)
    dir2=dir+file.split("&")[0]+'/'
    if not os.path.exists(dir2):
        os.makedirs(dir2)
    if 'main' in file:
        path_new=dir2+'主图.'+file.split(".")[-1]
        shutil.copy(path,path_new)
    if 'front' in file and 'pic' not in file:
        path_new=dir2+'前.'+file.split(".")[-1]
        shutil.copy(path,path_new)
    if 'back' in file and 'pic' not in file:
        path_new=dir2+'后.'+file.split(".")[-1]
        shutil.copy(path,path_new)
    if 'square' in file:
        path_new=dir2+'方图.'+file.split(".")[-1]        
        shutil.copy(path,path_new)
    if 'pic' in file:
        path_new=dir2+file       
        shutil.copy(path,path_new)
    if 'detail' in file:
        num=1
        while True:
            path_new=dir2+'详情'+str(num)+'.'+file.split(".")[-1]
            if not os.path.exists(path_new):
                shutil.copy(path,path_new)
                break
            else:
                num+=1